package com.changgou.order.task;

import com.alibaba.fastjson.JSON;
import com.changgou.order.dao.TaskMapper;
import com.changgou.order.pojo.Task;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class QueryPointTask {
    //扫描定时任务并发送消息到队列
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/2 * * * * ?") //每两秒执行一次定时任务
    public void queryTask() {
        //1.获取小于当前时间的系统数据
        List<Task> taskList = taskMapper.findTaskLessThanCurrentTime(new Date());
        if (taskList != null && taskList.size() > 0) {
            //如果存在定时任务，则往队列中发送数据
            for (Task task : taskList) {
                //2.将任务发送到消息队列上
                rabbitTemplate.convertAndSend(task.getMqExchange(), task.getMqRoutingkey(), JSON.toJSONString(task));
            }
        }
        System.out.println("订单服务向添加积分服务队列发送了一条消息");
    }
}
